package org.example;

import okhttp3.*;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.List;

public class TranslationSDK {
    public static final String API_KEY = "Your API_KEY";
    public static final String SECRET_KEY = "Your SECRET_KEY";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String []args) throws IOException{
        GUI();
    }

    /**
     * 根据类型获取请求参数
     *
     * @param type 翻译类型 1：汉译英 2：英译汉
     * @param q    待翻译文本
     * @return 请求参数
     */
    public static JSONObject getRequestParameters(int type, String q){
        //创建JSON对象
        JSONObject jsonObject = new JSONObject();
        Object obj = null;
        //根据类型向JSON对象中添加数据
        if (type == 1){
            jsonObject.put("from", "zh");
            jsonObject.put("to", "en");
        }else if (type == 2){
            jsonObject.put("from", "en");
            jsonObject.put("to", "zh");
        }
        jsonObject.put("q", q);
        //jsonObject.put("termIds", "https://www.aminer.cn/ml_taxonomy");
        //将JSON对象以字符串的形式打印
        System.out.println("the request parameters is " + jsonObject);
        return jsonObject;
    }



    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    public static void GUI() {
//        JFrame frame = new JFrame("百度翻译");
//        frame.setSize(500, 350);
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
//        Container container = frame.getContentPane();
//        container.setLayout(new FlowLayout());
//
//        JTextField inputTextField = new JTextField(20);
//        JButton translateToEnglishButton = new JButton("汉译英");
//        JButton translateToChineseButton = new JButton("英译汉");
//        JTextField outputTextField = new JTextField(20);
//        outputTextField.setEditable(false);
//
//        container.add(inputTextField);
//        container.add(translateToEnglishButton);
//        container.add(translateToChineseButton);
//        container.add(outputTextField);


        JFrame frame = new JFrame("百度翻译");
        frame.setSize(500, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container container = frame.getContentPane();
        container.setLayout(null); // 设置为null，让容器自己管理布局

        JTextField inputTextField = new JTextField(20);
        inputTextField.setBounds(50, 80, 220, 30); // 设置位置和大小
        container.add(inputTextField);

        JButton translateToEnglishButton = new JButton("汉译英");
        translateToEnglishButton.setBounds(280, 80, 80, 30); // 设置位置和大小
        container.add(translateToEnglishButton);

        JButton translateToChineseButton = new JButton("英译汉");
        translateToChineseButton.setBounds(370, 80, 80, 30); // 设置位置和大小
        container.add(translateToChineseButton);

        JTextField outputTextField = new JTextField(20);
        outputTextField.setEditable(false);
        outputTextField.setBounds(50, 150, 400, 30); // 设置位置和大小
        container.add(outputTextField);

        // 将container居中显示
        //container.setLocationRelativeTo(null);

        frame.setVisible(true);

        translateToEnglishButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    translate(inputTextField, outputTextField, 1);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        translateToChineseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    translate(inputTextField, outputTextField, 2);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        frame.setVisible(true);
    }

    public static void translate(JTextField inputTextField, JTextField outputTextField, int type) throws IOException {
        String query = inputTextField.getText();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, getRequestParameters(type, query).toString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String jsonString = response.body().string();
        System.out.println(jsonString);

        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject resultObject = jsonObject.getJSONObject("result");
        String dstValue = resultObject.getJSONArray("trans_result").getJSONObject(0).getString("dst");
        System.out.println(dstValue);

        outputTextField.setText(dstValue);
    }

}
